package com.tanhua.dubbo.api;

import com.tanhua.domain.mongo.RecommendUser;
import com.tanhua.domain.vo.PageResult;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

/**
 * @Classname RecommendUserApiImpl
 * @Description TODO
 * @Date 2021/3/9 21:06
 * @Created by gan
 */
@Service
public class RecommendUserApiImpl implements RecommendUserApi{
    @Autowired
    private MongoTemplate mongoTemplate;
    @Override
    public RecommendUser queryWithMaxScore(Long userId) {

        /**
         * 根据toUserId查询 recommend_user , 根据score 排序，找第一条
         */
        Criteria criteria = Criteria.where("toUserId").is(userId);

        Query query = new Query(criteria).
                with(Sort.by(Sort.Order.desc("score")))
                .limit(1);

        return mongoTemplate.findOne(query,RecommendUser.class);
    }

    //推荐列表，分页查询
    @Override
    public PageResult findPage(Integer page, Integer pagesize, Long userId) {
        Query query =new Query();
        //查询的条件  id
        query.addCriteria(Criteria.where("toUserId").is(userId));
        //获取总记录数
        long total = mongoTemplate.count(query, RecommendUser.class);
        //分页参数设置
        PageRequest pageRequest=PageRequest.of(page-1,pagesize,Sort.by(Sort.Order.desc("score")));
        query.with(pageRequest);
        //查询分页结果集
        List<RecommendUser> recommendUserList=mongoTemplate.find(query,RecommendUser.class);
        //封装返回
        PageResult<RecommendUser> pageResult = new PageResult<RecommendUser>();
        pageResult.setItems(recommendUserList);
        pageResult.setPage((long)page);
        pageResult.setPagesize((long)pagesize);
        pageResult.setCounts(total);
        // 计算总页数
        long pages = total/pagesize;
        pages+=total%pagesize>0?1:0;
        pageResult.setPages(pages);

        return pageResult;
    }



    //查询缘分值
    @Override
    public Double queryForScore(Long userId, Long toUserId) {
        //创建查询条件
        Query query=new Query();
        query.addCriteria(Criteria.where("toUserId").is(toUserId).and("userId").is(userId));
        //查询，排序
        query.with(Sort.by(Sort.Order.desc("date")));
        RecommendUser user = mongoTemplate.findOne(query, RecommendUser.class);
        if(user==null){
            return 95d;
        }
        return user.getScore();
    }




}
